package com.easy.dn.utils;

import android.content.res.AssetManager;

import com.easy.common.commonutils.StringUtils;
import com.easy.dn.app.GlobalApplication;
import com.easy.dn.bean.JsonDataBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 *  方便获取本项目所需要的数据
 * Created by 丁宁
 * on 2017/9/22.
 */

public class CommonDataUtil {


    private static List<JsonDataBean> mJsonDataList;
    private static String jsonStr = "";

    /**
     * 读取assets目录下的json文件
     * @return
     */
    public static String getJson(String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = GlobalApplication.getAppContext().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonStr = stringBuilder.toString();
        return  jsonStr;
    }

    public static List<JsonDataBean>   getJsonList(String fileName,String dataName) {

        if (StringUtils.isEmpty(jsonStr)){
            jsonStr = getJson(fileName);
        }
        JSONObject data = null;
        Gson gson = new Gson();
        try {
            data = new JSONObject(jsonStr);
            JSONArray    tradeList = data.optJSONArray(dataName);
            mJsonDataList = gson.fromJson(tradeList.toString(), new TypeToken<List<JsonDataBean>>() {}.getType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mJsonDataList;
    }

}
